package cn.liziguo.tank.script;

import cn.liziguo.tank.util.Time;
import com.almasb.fxgl.dsl.FXGL;
import com.almasb.fxgl.entity.component.Component;
import com.almasb.fxgl.time.TimerAction;
import javafx.scene.control.Label;
import javafx.scene.paint.Color;
import javafx.util.Duration;

/**
 * @author Liziguo
 * @date 2022-07-09 16:31:38
 */
public class WordComponent extends Component {

    private final Label label = new Label();
    private long lastTime = System.nanoTime();
    private int fps;
    private int fpsRecord;
    private TimerAction run;

    public WordComponent() {
        label.setTextFill(Color.WHITE);
    }

    @Override
    public void onAdded() {
        FXGL.getGameScene().getContentRoot().getChildren().add(label);
        run = FXGL.run(() -> {
            fpsRecord = fps;
            fps = 0;
        }, Duration.seconds(1));
    }

    @Override
    public void onUpdate(double tpf) {
        // 获取上一帧所花时间 存入全局变量
        // Time.deltaTime = tpf;
        final long time = System.nanoTime();
        final long diff = time - lastTime;
        Time.deltaTime = diff / 1000000000.0;
        lastTime = time;
        fps++;
        label.setText("fps:" + fpsRecord + "\n实例:" + FXGL.getGameWorld().getEntities().size());
    }

    @Override
    public void onRemoved() {
        FXGL.getGameScene().getContentRoot().getChildren().remove(label);
        run.expire();
    }
}
